package com.pinda.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pinda.authorization.entity.LoginLog;
import com.pinda.authorization.entity.User;
import com.pinda.commonutils.Key;
import com.pinda.mapper.LoginLogMapper;
import com.pinda.mapper.UserMapper;
import com.pinda.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author 黄杰
 * @since 2023-06-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private LoginLogMapper loginLogMapper;

    @Override
    public SaResult doLogin(String username, String password,String browsers,String operatingSystem,String timeStamp) {
        User user = this.userMapper.selectOne(new QueryWrapper<User>().eq("account", username));
        System.out.println(user);
        if(!ObjectUtils.isEmpty(user)){
            //根据私钥解密
            String pwd = Key.rsaDecryptByPrivate(user.getPassword());
            if(password.equals(pwd)){
                int i = this.loginLogMapper.insert(new LoginLog(null, null, user.getId(), user.getName(), user.getAccount(), null, timeStamp, null, browsers, null, operatingSystem, null, null, null));
                if(i>0){
                    //TODO 将用户ID存储在StpUtil中
                    StpUtil.login(user.getId());
                    //TODO 获取token信息
                    SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
                    //TODO 返回给前端
                    return SaResult.data(tokenInfo);
                }
            }
        }
        return SaResult.error("账号或密码错误，请重新输入！！！");
    }
}
